﻿#region Copyright information
// 
// Copyright © 2005-2013 Yongkee Cho. All rights reserved.
// 
// This code is a part of the Biological Object Library and governed under the terms of the
// GNU Lesser General  Public License (LGPL) version 2.1 which accompanies this distribution.
// For more information on the LGPL, please visit http://bol.codeplex.com/license.
// 
// - Filename: MixtureBase.cs
// - Author: Yongkee Cho
// - Email: yongkeecho@gmail.com
// - Date Created: 2012-09-06 11:39 AM
// - Last Modified: 2013-01-25 3:59 PM
// 
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BOL.Maths.Distributions
{
    public abstract class MixtureModelBase<T> : NomialDistributionBase<IUnivariateDistribution<T>>, IMixture<T>
        where T : struct, IComparable, IComparable<T>, IEquatable<T>
    {
        #region Constructor

        protected MixtureModelBase(IDictionary<IUnivariateDistribution<T>, double> probabilityTable)
            : base(probabilityTable) { }

        #endregion

        #region Public methods

        public double Pdf(T[] value)
        {
            if (value == null)
                throw new ArgumentNullException("value");

            if (value.Length != K)
                throw new ArgumentException();

            return ProbabilityTable.Zip(value, (p, v) => p.Value * p.Key.Pdf(v)).Sum();
        }

        public T[] Sample(Random r)
        {
            return ProbabilityTable.Select(x => x.Key.Sample(r)).ToArray();
        }

        #endregion

        #region Object overriden

        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.AppendLine("Mixture model = ");
            foreach (var p in ProbabilityTable)
                sb.AppendFormat("\t{0:F3} x {1}\n", p.Value, p.Key);
            return sb.ToString();
        }

        #endregion
    }
}
